package com.example.network.parse.xml

import android.os.Bundle
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import com.example.network.databinding.ActivityXmlBinding
import com.example.network.util.HttpUtil
import okhttp3.Call
import okhttp3.Callback
import okhttp3.Response
import org.xml.sax.InputSource
import org.xmlpull.v1.XmlPullParser
import org.xmlpull.v1.XmlPullParserFactory
import java.io.IOException
import java.io.StringReader
import javax.xml.parsers.SAXParserFactory
import kotlin.concurrent.thread

class XmlActivity : AppCompatActivity() {
    private lateinit var binding: ActivityXmlBinding
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        binding = ActivityXmlBinding.inflate(layoutInflater)
        val view = binding.root
        setContentView(view)
        ViewCompat.setOnApplyWindowInsetsListener(view) { v, insets ->
            val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars())
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom)
            insets
        }

        sendRequestWithOkHttp()
    }

    private fun sendRequestWithOkHttp() {
        thread {
            val mocker = XmlMocker("/get_data.xml")
            HttpUtil.sendOkhttpRequest(mocker.baseUrl, object : Callback {
                override fun onFailure(call: Call, e: IOException) {
                    e.printStackTrace()
                }

                override fun onResponse(call: Call, response: Response) {
                    val responseData = response.body?.string()
                    if (responseData != null) {
                        parseXMLWithPull(responseData)
//                        parseXMLWithSax(responseData)
                    }
                }
            })
        }
    }

    /**
     * 解析xml数据
     */
    private fun parseXMLWithPull(xmlData: String) {
        try {
            var id = ""
            var name = ""
            var version = ""
            val buffer = StringBuilder()

            val factory = XmlPullParserFactory.newInstance()
            val xmlPullParser = factory.newPullParser()
            xmlPullParser.setInput(StringReader(xmlData))

            var eventType = xmlPullParser.eventType
            while (eventType != XmlPullParser.END_DOCUMENT) {
                val nodeName = xmlPullParser.name
                when (eventType) {
                    // 开始解析某个节点
                    XmlPullParser.START_TAG -> {
                        when (nodeName) {
                            "id" -> id = xmlPullParser.nextText()
                            "name" -> name = xmlPullParser.nextText()
                            "version" -> version = xmlPullParser.nextText()
                        }
                    }
                    // 完成解析某个节点
                    XmlPullParser.END_TAG -> {
                        if ("app" == nodeName) {
                            buffer.append("id: $id, name: $name, version: $version\n")
                        }
                    }
                }
                eventType = xmlPullParser.next()
                showResponse(buffer.toString())
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    /**
     * 使用 SAX 解析 XML
     */
    private fun parseXMLWithSax(xmlData: String) {
        try {
            val factory = SAXParserFactory.newInstance()
            val xmlReader = factory.newSAXParser().xmlReader
            val handler = ContentHandler()
            xmlReader.contentHandler = handler
            xmlReader.parse(InputSource(StringReader(xmlData)))
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    private fun showResponse(text: String) {
        runOnUiThread {
            // 在主线程中更新 UI
            binding.responseText.text = text
        }
    }
}